# -*- coding: utf-8 -*-
import logging

from common.mch import handler as mch_handler
from common.order import db as order_db
from common.order import admin_db as admin_order_db
from common.order_inquiry import db as order_inquiry_db
from common.order_inquiry import handler as order_inquiry_handler
from common.utils import exceptions as err
from common.utils.api import check_params, get_client_ip
from common.utils.decorator import response_wrapper
from django.views.decorators.http import require_POST

_LOGGER = logging.getLogger(__name__)


@require_POST
@response_wrapper
def create(request):
    params = request.POST.dict()
    _LOGGER.info('create order inquiry data : %s', params)
    check_params(params, ['order_inquiry_no', 'mch_id', 'out_trade_no',
                          'user_id', 'username', 'amount',
                          'transaction_time', 'receipt', 'notify_url', 'sign'],
                 param_type_dct={
                     'mch_id': basestring,
                     'out_trade_no': basestring, })

    sign = params['sign']
    params.pop('sign')
    mch_id = params['mch_id']
    calculated_sign = mch_handler.generate_sign(mch_id, params)
    if sign != calculated_sign:
        raise err.AuthenticateError('sign error')
    params['mch_create_ip'] = get_client_ip(request)
    params['sign'] = sign

    existing_order_inquiry = order_inquiry_db.get_order_inquiry(params['order_inquiry_no'])
    if existing_order_inquiry:
        raise err.DataError('order_inquiry_no {} already exists.'.format(params['order_inquiry_no']))


    existing_pay_order = order_db.get_order(params['mch_id'], params['out_trade_no'])
    if not existing_pay_order:
        raise err.DataError('out_trade_no {} not found in pay order.'.format(params['out_trade_no']))

    params['service'] = existing_pay_order.service
    existing_pay_order.order_inquiry_status = 0
    admin_order_db.upsert_order(existing_pay_order.as_dict(), int(existing_pay_order.id))
    order_inquiry_handler.check_receipt(params['receipt'])
    order_inquiry = order_inquiry_handler.create(params)
    return order_inquiry


@require_POST
@response_wrapper
def query(request):
    params = request.POST.dict()
    _LOGGER.info('query order inquiry data : %s', params)

    check_params(params, ['mch_id', 'order_inquiry_no', 'out_trade_no', 'sign'],
                 param_type_dct={'mch_id': basestring,
                                 'out_trade_no': basestring,
                                 })

    sign = params['sign']
    params.pop('sign')
    mch_id = params['mch_id']
    order_inquiry_no = params['order_inquiry_no']
    out_trade_no = params['out_trade_no']
    calculated_sign = mch_handler.generate_sign(mch_id, params)
    if sign != calculated_sign:
        raise err.AuthenticateError('sign error')
    order_inquiry_info = order_inquiry_handler.get_order_inquiry_by_mch(mch_id, order_inquiry_no, out_trade_no)
    return order_inquiry_info
